<template>
  <div class="add-plan-dialog" v-if="dialogVisible">
    <!-- 弹窗 -->
    <div class="dialog-container">
      <!-- 关闭按钮 -->
      <div class="close" @click="handleClose">X</div>

      <!-- 内容区域 -->
      <div v-if="currentStep === 1" class="content step1">
        <div class="form-group">
          <label>预案名称</label>
          <el-input
            class="custom-input"
            v-model="planForm.planName"
            placeholder="请输入"
          ></el-input>
        </div>
        <div class="form-group">
          <label>轮巡间隔</label>
          <el-input
            class="custom-input"
            v-model="planForm.interval"
            placeholder="请输入"
          >
            <template #append>秒</template>
          </el-input>
        </div>
        <div class="form-group">
          <label>预案分类</label>
          <el-select
            v-model="planForm.planType"
            class="custom-select"
            placeholder="请选择"
          >
            <el-option
              v-for="(option, index) in categoryOptions"
              :key="index"
              :label="option.value"
              :value="option.code"
            ></el-option>
          </el-select>
        </div>
        <div class="action">
          <el-button type="danger" @click="handleClose">取消</el-button>
          <el-button
            type="primary"
            :disabled="!isValidStep1"
            @click="handleNextStep"
            >下一步</el-button
          >
        </div>
      </div>
      <div v-else class="content step2">
        <div class="search-box">
          <div class="titleBox">
            <div class="line"></div>
            <div class="title">高低点配置</div>
          </div>
          <div class="search-content">
            <img
              class="img"
              @click="handleSearch"
              src="/images/new/searchbtn.png"
            />
            <div class="searchbg">
              <el-input v-model="keyword" placeholder="请输入搜索关键词" />
            </div>
          </div>
        </div>

        <div class="config-area">
          <!-- 高点列表（左侧） -->
          <div class="high-list">
            <div class="list-title">选择高点</div>
            <div class="high-items">
              <div
                v-for="item in highOptions"
                :key="item.value"
                class="high-item"
                :class="{ active: selectedHigh.includes(item.value) }"
                @click="handleHighItemClick(item)"
              >
                {{ item.label }}
              </div>
            </div>
          </div>

          <!-- 低点列表（右侧） -->
          <div class="low-list">
            <div class="list-title">
              选择低点
              <span class="selected-count"
                >（已选{{ selectedLows.length }}个）</span
              >
            </div>
            <div class="low-items">
              <el-checkbox-group
                v-model="selectedLows"
                class="low-checkbox-group"
              >
                <el-checkbox
                  v-for="item in lowOptions"
                  :key="item.value"
                  :label="item.value"
                  class="custom-checkbox"
                >
                  <span class="label">{{ item.label }}</span>
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </div>

        <div class="action">
          <el-button type="danger" @click="handlePrevStep">上一步</el-button>
          <el-button
            type="primary"
            :disabled="!isValidStep2"
            @click="handleSave"
            >保存</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
const emit = defineEmits(["closeDig"]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
});

const dialogVisible = ref(false);
const keyword = ref(""); // 搜索关键词

// 弹窗步骤状态
const currentStep = ref(1); // 当前步骤

// 预案表单数据
const planForm = reactive({
  planName: "", // 预案名称
  interval: "", // 轮巡间隔
  planType: "", // 预案分类
});

// 预案分类选项
const categoryOptions = ref([]);

// 高点选项
const highOptions = ref([]);
const selectedHigh = ref(""); // 用户选择的高点

// 低点选项
const lowOptions = ref([]);
const selectedLows = ref([]); // 用户选择的低点

watch(
  () => props.visible,
  (newVal) => {
    let store = useMyStore();
    console.log("store.params.editPlanId", store.params.ya);
    dialogVisible.value = newVal;
    if (!newVal) {
      // 弹窗关闭时，清空数据
      resetForm();
    } else {
      // 弹窗打开时，根据是否有editPlanId来决定是否加载数据
      if (store.params.ya) {
        // 直接回显store.params.ya中的数据
        displayPlanData(store.params.ya);
      } else {
        // 如果没有预案数据，清空editPlanId
        // 清空表单数据
        resetForm();
      }
    }
  }
);
// 回显预案数据
const displayPlanData = (planData) => {
  // 回显第一步表单数据
  planForm.planName = planData.planName;
  planForm.interval = planData.interval || ""; // 确保有默认值
  planForm.planType = planData.planType;

  // 回显第二步数据
  selectedHigh.value = planData.highCameraId;
  selectedLows.value = planData.lowCameraIds || [];

  // 加载高点选项
  loadHighOptions().then(() => {
    // 加载对应的低点选项
    loadLowOptions();
  });
};
// 保留原始低点数据用于过滤
const rawLowOptions = ref([]);

// 监听关键词变化进行过滤
watch(keyword, (newVal) => {
  console.log("搜索关键词变化:", newVal);

  if (!rawLowOptions.value.length) return;
  if (!newVal) {
    // 空关键词时恢复原始数据
    lowOptions.value = [...rawLowOptions.value];
    return;
  }
  // 执行过滤（根据设备名称模糊匹配）
  lowOptions.value = rawLowOptions.value.filter((item) =>
    item.label.toLowerCase().includes(newVal.toLowerCase())
  );
});
// 搜索方法
const handleSearch = () => {
  console.log("执行搜索，当前高点:", selectedHigh.value);
  if (selectedHigh.value) {
    ElMessage.warning("请先选择高点");
    return;
  }
  // 执行搜索
  loadLowOptions();
};

// 验证第一步是否填写完整
const isValidStep1 = () => {
  return planForm.planName && planForm.interval && planForm.planType;
};

// 验证第二步是否填写完整
const isValidStep2 = () => {
  return selectedHigh.value && selectedLows.value.length > 0;
};
// 初始化表单数据
const resetForm = () => {
  currentStep.value = 1;
  planForm.planName = "";
  planForm.interval = "";
  planForm.planType = "";
  selectedHigh.value = "";
  selectedLows.value = [];
  keyword.value = "";
};
// 打开弹窗
const openDialog = () => {
  console.log("打开弹窗");
  dialogVisible.value = true;
};

// 关闭弹窗
const handleClose = () => {
  dialogVisible.value = false;
  emit("closeDig");
};

// 点击下一步
const handleNextStep = () => {
  if (!isValidStep1()) {
    ElMessage.warning("请填写完整第一步信息");
    return;
  }
  currentStep.value = 2;
  loadHighOptions(); // 加载高点选项
};

// 点击上一步
const handlePrevStep = () => {
  currentStep.value = 1;
};

const handleHighItemClick = (item) => {
  // 单选逻辑：取消之前选中，设置当前选中
  if (selectedHigh.value.includes(item.value)) {
    selectedHigh.value = "";
  } else {
    selectedHigh.value = item.value;
  }

  // 加载对应低点
  loadLowOptions();
};
// 加载高点选项
const loadHighOptions = async () => {
  try {
    const response = await useApi.post("/dynamicview/ar/highandlows", {});
    console.log(response.data);
    highOptions.value = response.data.highList.map((el) => ({
      value: el.cameraId,
      label: el.cameraName,
    }));
  } catch (error) {
    ElMessage.error("加载高点失败");
  }
};

// 根据高点加载低点选项
const loadLowOptions = async () => {
  try {
    const response = await useApi.post("/dynamicview/ar/getlowsbyhigh", {
      deviceId: selectedHigh.value,
    });
    // 保存原始数据到rawLowOptions
    rawLowOptions.value = response.data.lowCameraList.map((el) => ({
      value: el.deviceId,
      label: el.deviceName,
    }));
    // 初始化过滤数据
    lowOptions.value = [...rawLowOptions.value];
    // 如果是编辑模式，保持已选中的低点
    if (selectedLows.value.length > 0) {
      // 过滤掉不存在的低点（防止数据不一致）
      selectedLows.value = selectedLows.value.filter((lowId) =>
        rawLowOptions.value.some((item) => item.value === lowId)
      );
    }
  } catch (error) {
    ElMessage.error("加载低点失败");
  }
};

// 保存预案
const handleSave = async () => {
  if (!isValidStep1()) {
    ElMessage.warning("请填写完整第一步信息");
    return;
  }
  if (!isValidStep2()) {
    ElMessage.warning("请完成高低点配置");
    return;
  }
  let store = useMyStore();
  const isEdit = !!store.params.ya;
  // 构建请求参数
  const params = {
    planName: planForm.planName,
    interval: planForm.interval,
    planType: planForm.planType,
    highCameraId: selectedHigh.value, // 根据接口要求调整
    lowCameraIds: selectedLows.value,
    optType: store.params.ya && store.params.ya.planId ? "U" : "A", // 如果有planId则为更新，否则为添加
    planId:
      store.params.ya && store.params.ya.planId ? store.params.ya.planId : "", // 如果是编辑模式，添加planId
  };

  try {
    const res = await useApi.post("/dynamicview/ar/inspection/edit", params);
    ElMessage.success("预案保存成功");
    handleClose(); // 关闭弹窗
  } catch (error) {
    ElMessage.error("保存失败");
  }
};
const getData = async () => {
  const res = await useApi.post("/dynamicview/ar/commonparams", {
    paramType: "plan_type",
  });
  categoryOptions.value = res.data.params;
};
// 初始化
onMounted(() => {
  console.log("onMounted  走没走啊", props.visible);

  if (props.visible) {
    openDialog();
  }
  getData();
  loadHighOptions();
});
</script>

<style lang="scss" scoped>
.add-plan-dialog {
  display: flex;
  justify-content: center;
  align-items: center;
  .dialog-container {
    border-radius: 10px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    width: 760px;
    height: 640px;
    background: url("/images/new/addPlanBg.png") no-repeat;
    background-size: 100% 100%;

    .close {
      position: absolute;
      top: 40px;
      right: 30px;
      width: 50px;
      height: 50px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 35px;
      color: #fff;
      cursor: pointer;
    }

    .content {
      &.step1 {
        margin: 90px 180px;

        .form-group {
          margin-bottom: 20px;

          label {
            display: block;
            margin-bottom: 10px;
            font-family: PingFangSC, PingFang SC;
            font-weight: 300;
            font-size: 20px;
            color: #ffffff;
            line-height: 23px;
            letter-spacing: 3px;
            text-align: left;
            font-style: normal;
          }
        }
      }

      &.step2 {
        margin: 90px 50px;
        .search-box {
          width: 100%;
          height: 50px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          .titleBox {
            display: flex;
            justify-content: center;
            align-items: center;
            .line {
              width: 5px;
              height: 21px;
              background: #3eeeff;
              margin-right: 10px;
            }
            .title {
              font-family: PingFangSC, PingFang SC;
              font-weight: 300;
              font-size: 23px;
              color: #ffffff;
              line-height: 32px;
              letter-spacing: 3px;
              text-shadow: 0px 1px 10px #003369;
              text-align: left;
              font-style: normal;
            }
          }
          .search-content {
            display: flex;
            align-items: center;
            padding: 0px 30px 0 30px;
            .img {
              width: 70px;
              height: 50px;
              cursor: pointer;
            }
            :deep(.searchbg) {
              width: 250px;
              height: 50px;
              background: transparent !important;
              box-shadow: none !important;
              .el-input {
                width: 100%;
                height: 100%;
                background: transparent !important;
                box-shadow: none !important;

                .el-input__wrapper {
                  background: transparent !important;
                  box-shadow: none !important;
                  background: url("/images/new/searchbg.png") no-repeat !important;
                  background-size: 100% 100% !important;
                }
                .el-input__inner {
                  background: transparent !important;
                  color: #b0d9ff !important;
                  font-size: 18px;
                  font-weight: 300 !important;
                  padding-left: 8px;
                  border: 0 !important;
                  &::placeholder {
                    color: #b0d9ff;
                  }
                }
              }
            }
          }
        }
        .highs-config,
        .lows-config {
          .form-group {
            margin-bottom: 20px;

            label {
              display: block;
              margin-bottom: 10px;
              font-family: PingFangSC, PingFang SC;
              font-weight: 300;
              font-size: 20px;
              color: #ffffff;
              line-height: 23px;
              letter-spacing: 3px;
              text-align: left;
              font-style: normal;
            }
          }
        }
      }

      .action {
        display: flex;
        justify-content: center;
        align-content: center;
        margin-top: 20px;
        gap: 10px;
        ::v-deep(.el-button) {
          width: 150px;
          height: 50px;
          background: linear-gradient(
            148deg,
            rgba(46, 233, 255, 0.72) 0%,
            #0f7bc4 100%
          );
          background-image: url("/public/images/btnZ.png");
          background-size: 100% 100%;
          background-repeat: no-repeat;
          position: relative;
          overflow: hidden;
          font-family: YouSheBiaoTiHei;
          font-size: 25px;
          color: #ffffff;
          &:hover {
            opacity: 0.9;
            box-shadow: 0px 4px 35px 0px #136e8c,
              inset 0px -10px 20px 0px rgba(192, 231, 255, 0.6);
          }

          &:active {
            transform: translateY(1px);
            box-shadow: 0px 2px 20px 0px #136e8c,
              inset 0px -5px 10px 0px rgba(192, 231, 255, 0.4);
          }

          /* 覆盖默认按钮样式 */
          &.el-button--primary {
            background-color: transparent;
            &:hover,
            &:focus,
            &:active {
              background-color: transparent;
              border-color: transparent;
            }
          }

          &.el-button--danger {
            background-color: transparent;
            &:hover,
            &:focus,
            &:active {
              background-color: transparent;
              border-color: transparent;
            }
          }
        }

        /* 调整按钮文字样式 */
        ::v-deep(.el-button__content) {
          font-family: PingFangSC, PingFang SC;
          font-weight: 400;
          font-size: 18px;
          letter-spacing: 2px;
          text-shadow: 0px 1px 3px rgba(0, 0, 0, 0.3);
        }
      }
    }
  }
}

:deep(.custom-input) {
  .el-input__wrapper {
    background: url("/images/new/inputBg.png") no-repeat !important;
    background-size: 100% 100% !important;
    box-shadow: none !important;
    border: none !important;
    &.is-focus {
      box-shadow: none !important;
      border: none !important;
    }
    .el-input__inner {
      background: transparent !important;
      border: none !important;
      height: 45px;
      line-height: 45px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 300;
      font-size: 20px;
      color: #a6e2fc !important;
      letter-spacing: 3px;
      text-align: left;
      font-style: normal;
      &::placeholder {
        font-family: PingFangSC, PingFang SC;
        font-weight: 300;
        font-size: 20px;
        color: #a6e2fc !important;
        letter-spacing: 3px;
        text-align: left;
        font-style: normal;
      }
      &:focus {
        outline: none !important;
      }
    }
  }

  // 数字输入框的追加样式
  .el-input-group__append {
    background: transparent !important;
    border: none !important;
    color: #fff !important;
    padding: 0 10px !important;
    box-shadow: none !important;
    margin-right: -40px !important;
    font-family: PingFangSC, PingFang SC;
    font-weight: 300;
    font-size: 20px;
    color: #ffffff;
    letter-spacing: 3px;
    text-align: left;
    font-style: normal;
    &:focus {
      outline: none !important;
    }
  }
}

::v-deep(.custom-select) {
  .el-input__wrapper {
    &.is-focus {
      box-shadow: none !important;
      border: none !important;
    }

    .el-input__inner {
      background: transparent !important;
      color: #ffffff !important;
      border: none !important;
      height: 45px;
      line-height: 45px;
    }
  }

  .el-select__placeholder {
    font-family: PingFangSC, PingFang SC !important;
    font-weight: 300 !important;
    font-size: 20px !important;
    color: #a6e2fc !important; /* 修改为你想要的颜色 */
    letter-spacing: 3px !important;
    text-align: left !important;
  }
  .el-select__selection {
    height: 45px;
    line-height: 45px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 300;
    font-size: 20px;
    letter-spacing: 3px;
    text-align: left;
    font-style: normal;
    color: #a6e2fc !important;
    &:focus {
      outline: none !important;
    }
  }
  .el-select__wrapper {
    background: url("/images/new/inputBg.png") no-repeat !important;
    background-size: 100% 100% !important;
    background-color: none !important;
    box-shadow: none !important;
  }

  // 下拉箭头样式
  .el-input__suffix {
    .el-icon {
      color: #fff !important;
    }
  }
}
/* 新增样式 */
.config-area {
  display: flex;
  gap: 10px;
  margin-top: 20px;

  .high-list,
  .low-list {
    flex: 1;

    .list-title {
      font-family: PingFangSC, PingFang SC;
      font-weight: 300;
      font-size: 20px;
      color: #ffffff;
      letter-spacing: 3px;
      text-shadow: 0px 1px 0px #003369;
      text-align: left;
      font-style: normal;
      margin-bottom: 10px;
      padding-left: 10px;
    }

    .low-select {
      width: 100%;

      /* 自定义下拉框样式 */
      :deep(.el-input__wrapper) {
        background: rgba(255, 255, 255, 0.1);
        border: 1px solid rgba(255, 255, 255, 0.3);
        border-radius: 4px;

        .el-input__inner {
          color: #fff;
          &::placeholder {
            color: rgba(255, 255, 255, 0.7);
          }
        }
      }
    }

    /* 多选样式 */
    :deep(.el-select__tags) {
      flex-wrap: nowrap;
      .el-tag {
        background: rgba(62, 238, 255, 0.2);
        border: none;
        color: #fff;
        margin: 2px;
      }
    }
  }
  /* 新增样式 */
  .high-items {
    width: 315px;
    height: 330px;
    max-height: 330px;
    overflow-y: auto;
    box-shadow: inset 0px 0px 60px 0px #45c0ff;
    border: 1px solid;
    border-image: linear-gradient(
        360deg,
        rgba(62, 176, 255, 1),
        rgba(255, 255, 255, 1)
      )
      1 1;

    .high-item {
      padding: 12px 15px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 300;
      font-size: 21px;
      color: #ffffff;
      line-height: 38px;
      letter-spacing: 1px;
      text-align: left;
      font-style: normal;
      cursor: pointer;

      &:hover {
        background: linear-gradient(90deg, #79e4ff, #3fa3ff);
        text-shadow: 0px 1px 7px #000;
      }

      &.active {
        background: linear-gradient(90deg, #79e4ff, #3fa3ff);
        text-shadow: 0px 1px 7px #000;
        position: relative;
      }
    }
  }
  /* 新增样式 */
  .low-items {
    max-height: 450px;
    overflow-y: auto;
  }
}

.low-checkbox-group {
  width: 315px;
  height: 330px;
  max-height: 330px;
  overflow-y: auto;
  box-shadow: inset 0px 0px 60px 0px #45c0ff;
  border: 1px solid;
  border-image: linear-gradient(
      360deg,
      rgba(62, 176, 255, 1),
      rgba(255, 255, 255, 1)
    )
    1 1;

  :deep(.el-checkbox) {
    display: flex;
    align-items: center;
    padding: 12px 15px;
    margin-top: 12px;
    font-family: PingFangSC, PingFang SC;
    font-weight: 300;
    font-size: 21px;
    color: #ffffff;
    line-height: 38px;
    letter-spacing: 1px;
    text-align: left;
    font-style: normal;
    .el-checkbox__input {
      margin-right: 10px;
      .el-checkbox__inner {
        width: 20px;
        height: 20px;
        border: 1px solid #fff;
        background: transparent;

        &::after {
          background: linear-gradient(153deg, #f0aa33 0%, #ffd62b 100%);
          border-radius: 4px;
          width: 6px;
          height: 10px;
        }
      }
    }

    .el-checkbox__label {
      font-family: PingFangSC, PingFang SC;
      font-weight: 300;
      font-size: 21px;
      color: #ffffff;
      line-height: 38px;
      letter-spacing: 3px;
      padding-left: 0px;
    }

    &.is-checked {
      .el-checkbox__inner {
        background: linear-gradient(153deg, #f0aa33 0%, #ffd62b 100%);
        border-radius: 4px;
        &::after {
          border-color: #fff;
        }
      }
    }
  }
}
</style>
